﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MOJsdk;
using System.Threading;
using System.Windows.Threading;
using System.Collections.ObjectModel;

namespace MojAddNewMovie
{
    /// <summary>
    /// Interaction logic for Control_AddNewMovie.xaml
    /// </summary>
    public partial class Control_AddNewMovie : UserControl
    {
        private ObservableCollection<MojWebMovie> _movies;

        public Control_AddNewMovie()
        {
            InitializeComponent();
            INIStyle();
            INIEvents();
        }

        private void INIStyle()
        {
            _btn_search.IsEnabled = false;
            _btnSelect.IsEnabled = false;
            _grid_back.Visibility = System.Windows.Visibility.Hidden;

            _grid.ApplyStyle("AddNewMovie_BackgroudGrid");
            _grid_back.ApplyStyle("AddNewMoview_WaitGrid");
            _txtBox_Search.ApplyStyle("AddNewMovie_TextBox_Search");
            _btn_search.ApplyStyle("AddNewMovie_Button_Search");
            _btnSelect.ApplyStyle("AddNewMovie_Button_Select");
            _proBar.ApplyStyle("AddNewMovie_ProgressBar");
            _listView.ApplyStyle("AddNewMovie_ListView");
        }
        private void INIEvents()
        {
            _txtBox_Search.TextChanged += TextChanged;
            _txtBox_Search.KeyDown += OnKeyDown;
            _txtBox_Search.GotFocus += OnFocus;
            _btn_search.Click += SearchMovie;
            _btnSelect.Click += SelectMovie;
            _listView.SelectionChanged += SelectionChanged;
            onMovieSelected += delegate { };
        }

        private void TextChanged(object sender, TextChangedEventArgs e)
        {
            string txt = _txtBox_Search.Text;

            if (txt == "Search...")
            {
                _btn_search.IsEnabled = false;
                return;
            }

            if (txt.Length > 2)
                _btn_search.IsEnabled = true;
            else
                _btn_search.IsEnabled = false;
        }
        private void OnFocus(object sender, RoutedEventArgs e)
        {
            if (_txtBox_Search.Text == "Search...")
                _txtBox_Search.Text = "";
        }
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
                SearchMovie(null, null);
        }
        private void SearchMovie(object sender, RoutedEventArgs e)
        {
            if (_txtBox_Search.Text.Length < 3)
                return;

            StartSearchMovie();
            
        }
        private void SelectMovie(object sender, RoutedEventArgs e)
        {
            int x = _listView.SelectedIndex;
            if (x == -1) return;

            MojWebMovie movie = _movies[x];

            if (movie.Cover != null)
            {
                movie.Cover.DownloadOriginalFile();
                string dest = System.IO.Path.Combine(MojFoldersEnum.ImagesFolder.Value(), string.Format("{0} ({1}).jpg", movie.Title, movie.Year));
                if (!System.IO.File.Exists(dest))
                    System.IO.File.Copy(movie.Cover.OriginalPath, dest);
                MoJBasicFile file = new MoJBasicFile(dest, 0, MOJFileTypes.CoverFile, movie.MovieId);
                MojHost.GetHost.MoJSystem.FilesInterop.AddNewFile(file);
            }

            if (MojHost.GetHost.MoJSystem.MoviesInterop.MovieExist(movie.MovieId))
            {
                MojHost.GetHost.ShowMessage("Movie exist in Database", "Error");
                return;
            }

            MoJBasicMovie m = new MoJBasicMovie(movie);
            MojHost.GetHost.MoJSystem.MoviesInterop.UpdateMovie(m);

            MojHost.GetHost.ReloadElementsInfo();
            onMovieSelected(this);
        }
        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int x = _listView.SelectedIndex;
            _btnSelect.IsEnabled = x != -1;
        }

        private void StartSearchMovie()
        {
            _grid_controls.IsEnabled = false;
            _grid_back.Visibility = System.Windows.Visibility.Visible;
            _listView.ItemsSource = null;

            string query = _txtBox_Search.Text;

            InternetInfo webInfo = new InternetInfo(TOOLS.TMDB_APIKey);
            webInfo.onError += delegate(ErrorReporter e)
            { MojHost.GetHost.ReportError(e); };

            webInfo.onSearchMovieCompleted += SearchCompleted;
            webInfo.SearchMovieAsync(query);
        }
        private void SearchCompleted(List<MojWebMovie> list)
        {
            foreach (var v in list)
                if (v.Cover != null)
                    v.Cover.DownloadThumbPath();

            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
            {
                _grid_controls.IsEnabled = true;
                _grid_back.Visibility = System.Windows.Visibility.Hidden;
                _movies = new ObservableCollection<MojWebMovie>(list);
                _listView.ItemsSource = _movies;
            });
        }

        public event CallEventHandler onMovieSelected;
    }
}
